package com.itany.cloud.config;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.loadbalancer.annotation.LoadBalancerClient;
import org.springframework.cloud.loadbalancer.core.RandomLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ReactorLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

/**
 * @author 石小俊
 */
@Configuration
// value属性:指定当前调用的服务是谁
// configuration:表示指定配置类是谁,直接指定当前类的class类型即可
@LoadBalancerClient(value = "cloud-nacos-provider",configuration = CustomLoadBalancerConfiguration.class)
public class CustomLoadBalancerConfiguration {

    /**
     *
     * @param environment
     * @param loadBalancerClientFactory
     * @return  返回的是ReactorLoadBalancer接口中的某个实现类,根据返回的实现类不同,其使用的负载均衡策略也不同
     * RoundRobinLoadBalancer:默认值,轮询负载均衡
     * RandomLoadBalancer:随机负载均衡
     */
    @Bean
    ReactorLoadBalancer<ServiceInstance> randomLoadBalancer(Environment environment,
                                                            LoadBalancerClientFactory loadBalancerClientFactory) {
        String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);
        return new RandomLoadBalancer(loadBalancerClientFactory
                .getLazyProvider(name, ServiceInstanceListSupplier.class),
                name);
    }
}
